package qwq.zyu.Hologram;

import eu.decentsoftware.holograms.api.DHAPI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class qwqSetScheduledUpdateHologramCommand implements CommandExecutor {
    private final Plugin plugin;
    private final qwqShowTop10ScoreboardCommand showTop10ScoreboardCommand;
    private final Map<String, BukkitRunnable> updatedTasks = new HashMap<>();



    public qwqSetScheduledUpdateHologramCommand(Plugin plugin, qwqShowTop10ScoreboardCommand showTop10ScoreboardCommand) {
        this.plugin = plugin;
        this.showTop10ScoreboardCommand = showTop10ScoreboardCommand;
    }

    public void clearAllTasks(){
        for (BukkitRunnable task: updatedTasks.values()){
            task.cancel();
        }
        updatedTasks.clear();
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if ( !(args.length>=9 && args.length<=10) ){
            sender.sendMessage(
                "用法: /qwq_set_scheduled_update_scoreboard <计分板名称> <降序？t/f> <把0放到末尾> <是否标序号？t/f> <隐藏0？t/f> <隐藏Vol? t/f> <tick美化成秒数? t/f> <动态效果启用?t/f> <周期 单位是tick>  [自定义标题]"
            );
            return false;
        }

        String scoreboardName = args[0];
        boolean isDescending = Boolean.parseBoolean(args[1]);
        boolean putZeroToEnd = Boolean.parseBoolean(args[2]);
        boolean isSN = Boolean.parseBoolean(args[3]);
        boolean hideZero = Boolean.parseBoolean(args[4]);
        boolean hideVol = Boolean.parseBoolean(args[5]);
        boolean tickToSecond = Boolean.parseBoolean(args[6]);
        boolean enableUpdate = Boolean.parseBoolean(args[7]);
        int t = Integer.parseInt(args[8]);


        final String customTitle = args.length==10 ? args[9] : null;

        Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
        Objective objective = scoreboard.getObjective(scoreboardName);

        if (objective == null) {
            sender.sendMessage("未找到计分板Hologram：" + scoreboardName);
            return false;
        }

        if ( enableUpdate ){
            if ( updatedTasks.containsKey(scoreboardName) ){
                sender.sendMessage("计分板Hologram " + scoreboardName + " 的更新任务已经在运行。");
                return false;
            }

            BukkitRunnable task = new BukkitRunnable() {
                @Override
                public void run() {
                    List<String> top10Lines = showTop10ScoreboardCommand.getTop10Players(objective, isDescending, putZeroToEnd, isSN, hideZero, hideVol, tickToSecond);
//                    List<String> top10Lines = showTop10ScoreboardCommand.getTop10Players_Heap(objective, isDescending, putZeroToEnd, isSN, hideZero, hideVol, tickToSecond);

                    if (top10Lines.equals(showTop10ScoreboardCommand.getCachedTop10(scoreboardName))){
                        return;
                    }

                    showTop10ScoreboardCommand.updateCache(scoreboardName, top10Lines);

                    if ( customTitle != null ){
                        String coloredCustomTitle = ChatColor.translateAlternateColorCodes('&', customTitle);
                        top10Lines.add(0, coloredCustomTitle);
                    }
                    if (DHAPI.getHologram(scoreboardName) != null ){
                        DHAPI.setHologramLines(
                            DHAPI.getHologram(scoreboardName), top10Lines
                        );
                    }
                }
            };

            task.runTaskTimer(plugin, 0, t);
            updatedTasks.put(scoreboardName, task);

            // 获取当前时间并格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = sdf.format(new Date());
            String logMessage = String.format(
                    "[%s] 更新任务已添加: %s, 当前任务数: %d", currentTime, scoreboardName, updatedTasks.size()
            );
            Bukkit.getServer().broadcastMessage(ChatColor.GREEN + logMessage);
            Bukkit.getLogger().info(logMessage);

            sender.sendMessage("已开启计分板Hologram " + scoreboardName + " 的更新任务。");
        } else {
            if ( updatedTasks.containsKey(scoreboardName) ){
                updatedTasks.get(scoreboardName).cancel();
                updatedTasks.remove(scoreboardName);
                sender.sendMessage("已停止计分板Hologram " + scoreboardName + " 的更新任务。");
            } else {
                sender.sendMessage("计分板 " + scoreboardName + " 的更新任务未在运行。");
            }
        }

        return true;

    }



}
